//
//  GWGoodsListView.m
//  ShandsMod
//
//  Created by zh_s on 4/22/21.
//  Copyright © 2021 zh_s. All rights reserved.
//

#import "GWGoodsListView.h"

#define HORIZONTAL_PADDING 7.0f
#define VERTICAL_PADDING   3.0f
#define LABEL_MARGIN       10.0f
#define BOTTOM_MARGIN      10.0f
#define KBtnTag            1000
#define R_G_B_16(rgbValue)\
\
[UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 \
alpha:1.0]


@interface GWGoodsListView (){
    
    CGFloat _KTagMargin;//左右tag之间的间距
    CGFloat _KBottomMargin;//上下tag之间的间距
    NSInteger _kSelectNum;//实际选中的标签数
    UIButton*_tempBtn;//临时保存对象

}

@end

@implementation GWGoodsListView

-(id)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    if (self) {
        _kSelectNum=0;
        _totalHeight=0;
        self.frame=frame;
        _tagArr=[[NSMutableArray alloc]init];
        /**默认是多选模式 */
        self.isSingleSelect=NO;

    }
    return self;
    
}
-(void)setTagWithTagArray:(NSArray*)arr{
//    [_tagArr removeAllObjects];
    
    previousFrame = CGRectZero;
    [_tagArr addObjectsFromArray:arr];
    [arr enumerateObjectsUsingBlock:^(HelpWordsModel *model, NSUInteger idx, BOOL *stop) {
    
        UIButton*tagBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        tagBtn.frame=CGRectZero;
        
        if(_canTouch){
            tagBtn.userInteractionEnabled=YES;
            
        }else{
            
            tagBtn.userInteractionEnabled=NO;
        }
//        tagBtn.selected = model.isSelected;
        [tagBtn setTitleColor:MAIN_BACKCOLOR forState:UIControlStateNormal];
//        [tagBtn setTitleColor:MAIN_ACTIVE_COLOR forState:UIControlStateSelected];
        tagBtn.titleLabel.font=FONT_NAME(FONT_Regular, 12);
        [tagBtn addTarget:self action:@selector(tagBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        NSString *name = model.name;
        tagBtn.selected = model.isSelected;
        [tagBtn setTitle:name forState:UIControlStateNormal];
        
        tagBtn.tag=KBtnTag+idx;
        tagBtn.layer.cornerRadius = 6;

        tagBtn.clipsToBounds = YES;
        NSDictionary *attrs = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:15]};
        
        
        CGSize Size_str=[name sizeWithAttributes:attrs];
        Size_str.width += HORIZONTAL_PADDING*3;
        
        CGRect newRect = CGRectZero;
        
        if (_canDelete) {
            Size_str.width = Size_str.width + 20;
            [tagBtn setImage:IMAGE_NAME(@"icon_tag_close1") forState:UIControlStateNormal];
        }
        if (_btnBackColor) {
            Size_str.height += 5*3;
        }else {
            Size_str.height += VERTICAL_PADDING*3;
        }

        if(_KTagMargin&&_KBottomMargin){
            
            if (previousFrame.origin.x + previousFrame.size.width + Size_str.width + _KTagMargin > self.bounds.size.width) {
                
                newRect.origin = CGPointMake(10, previousFrame.origin.y + Size_str.height + _KBottomMargin);
                self.totalHeight +=Size_str.height + _KBottomMargin;
            }
            else {
                newRect.origin = CGPointMake(previousFrame.origin.x + previousFrame.size.width + _KTagMargin, previousFrame.origin.y);
                
            }
            [self setHight:self andHight:self.totalHeight+Size_str.height + _KBottomMargin];

            
        }else{
        if (previousFrame.origin.x + previousFrame.size.width + Size_str.width + LABEL_MARGIN > self.bounds.size.width) {
            
            newRect.origin = CGPointMake(10, previousFrame.origin.y + Size_str.height + BOTTOM_MARGIN);
            self.totalHeight +=Size_str.height + BOTTOM_MARGIN;
        }
        else {
            newRect.origin = CGPointMake(previousFrame.origin.x + previousFrame.size.width + LABEL_MARGIN, previousFrame.origin.y);
            
        }
            [self setHight:self andHight:self.totalHeight+Size_str.height + BOTTOM_MARGIN];
        }

        if (_btnBackColor) {
            tagBtn.backgroundColor = _btnBackColor;
            [tagBtn setTitleColor:RGB(175, 182, 203) forState:UIControlStateNormal];
            [tagBtn setTitleColor:MAIN_ACTIVE_COLOR forState:UIControlStateSelected];
        }else {
            tagBtn.backgroundColor = RGBA(234, 237, 255, 1);
        }

        newRect.size = Size_str;
        [tagBtn setFrame:newRect];
        if (_canDelete) {
            //https://www.likecs.com/show-308020885.html
            tagBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -tagBtn.imageView.frame.size.width, 0, (tagBtn.imageView.frame.size.width));
            tagBtn.imageEdgeInsets = UIEdgeInsetsMake(0, (tagBtn.titleLabel.frame.size.width)+8, 0, -(tagBtn.titleLabel.frame.size.width));
        }
        previousFrame = tagBtn.frame;
        [self setHight:self andHight:self.totalHeight+Size_str.height + BOTTOM_MARGIN];
        [self addSubview:tagBtn];


    }];
    if(_GBbackgroundColor){
        
        self.backgroundColor=_GBbackgroundColor;
        
    }else{
        
        self.backgroundColor= [UIColor clearColor];
        
    }
    

}
#pragma mark-改变控件高度
- (void)setHight:(UIView *)view andHight:(CGFloat)hight
{
    CGRect tempFrame = view.frame;
    tempFrame.size.height = hight;
    view.frame = tempFrame;
}
-(void)tagBtnClick:(UIButton*)button{
    NSInteger btnTag = button.tag - KBtnTag;
    
    NSMutableArray *allTagArr = [NSMutableArray arrayWithCapacity:0];
    [allTagArr addObjectsFromArray:_tagArr];
    HelpWordsModel *model = allTagArr[btnTag];
    [allTagArr removeObjectAtIndex:btnTag];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(updateDataArrWithArr:withDeleteModel:withIsDelete:)]) {
        [self.delegate updateDataArrWithArr:allTagArr withDeleteModel:model withIsDelete:YES];
    }else {
        if(_isSingleSelect){
            if(button.selected){
                
                button.selected=!button.selected;
                
            }else{
                
                _tempBtn.selected=NO;
                _tempBtn.backgroundColor=[UIColor whiteColor];
                 button.selected=YES;
                _tempBtn=button;
                
            }
            
        }else{
            
            button.selected=!button.selected;
        }
        
        if(button.selected==YES){
            button.layer.borderColor = MAIN_ACTIVE_COLOR.CGColor;
            button.layer.borderWidth = 0.5f;
        }else if (button.selected==NO){
            button.layer.borderColor = UIColor.clearColor.CGColor;
            button.layer.borderWidth = 0.5f;
        }
        
        ///单选逻辑
        if (_isSingleSelect) {
            
            [_tagArr enumerateObjectsUsingBlock:^(HelpWordsModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
    //            obj.isSelected = NO;
            }];
            
            for (UIView*view in self.subviews) {
                UIButton*tempBtn=(UIButton*)view;
                if (tempBtn.tag == button.tag) {
                    tempBtn.selected = YES;
                }else {
                    tempBtn.selected = NO;
                    tempBtn.backgroundColor = RGBA(234, 237, 255, 1);
                }
            }
        }
        
        [self didSelectItems];
    }
    
   
    
    
}
-(void)didSelectItems{

    NSMutableArray*arr = [[NSMutableArray alloc]init];


    [_tagArr enumerateObjectsUsingBlock:^(HelpWordsModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        obj.isSelected = NO;
    }];

    for(UIView*view in self.subviews){

        if([view isKindOfClass:[UIButton class]]){

            UIButton*tempBtn=(UIButton*)view;
            
            tempBtn.enabled=YES;
            if (tempBtn.selected==YES) {
                HelpWordsModel *model =_tagArr[tempBtn.tag-KBtnTag];
                model.isSelected = YES;
                [arr addObject:model];
                _kSelectNum=arr.count;
            }
        }
    }
    if(_kSelectNum==self.canTouchNum){
        
        for(UIView*view in self.subviews){

            UIButton*tempBtn=(UIButton*)view;

         if (tempBtn.selected==YES) {
             tempBtn.enabled=YES;
             
         }else{
             tempBtn.enabled=NO;
             
         }
    }
    }
    self.didselectItemBlock(arr);
    
    
}
-(void)setMarginBetweenTagLabel:(CGFloat)Margin AndBottomMargin:(CGFloat)BottomMargin{
    
    _KTagMargin=Margin;
    _KBottomMargin=BottomMargin;

}



@end
